package cn.tao.org.controller;

import cn.tao.org.domain.Department;
import cn.tao.org.query.DepartmentQuery;
import cn.tao.org.service.IDepartmentService;
import cn.tao.utils.AjaxResult;
import cn.tao.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/department")
//@CrossOrigin
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 新增和修改
     * @RequestBody 接收一个json类型的对象
     * @param department
     * @return
     */
    @PutMapping
    public AjaxResult savAndUpt(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     *("/{id}"):要与@PathVariable中的参数对应
     * @param id
     * @return
     */
    @DeleteMapping("/detail/{id}")
    public AjaxResult delById(@PathVariable("id") Long id){
        try{
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 根据id查询一个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department findDepartmentById(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<Department> findDepartments(){
       return departmentService.loadAll();
    }

    /**
     * 高级查询和分页
     * @param query
     * @return
     */
    @PostMapping
    public QueryResult<Department> findDepartmentByQuery(@RequestBody DepartmentQuery query){

        return departmentService.findByQuery(query);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody Long[] ids){
        try {
            departmentService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 查询上级部门多级展示
     * @return
     */
    @GetMapping("/loadTree")
    public List<Department> loadDeptTree(){
        return departmentService.loadDeptTree();

    }

}
